package com.kehao.leetcode.basic.tree;


import java.util.*;

public class TreeSolution4 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> floor = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if(root==null)
            return result;
        queue.add(root);
        floor.add(1);

        while (!queue.isEmpty()){
            TreeNode node = queue.remove();
            int level = floor.remove();
            List<Integer> floorList ;
            if(result.size()<level){
                floorList = new ArrayList<>();
                result.add(floorList);
            }else {
                floorList = result.get(level-1);
            }
            floorList.add(node.val);
            if(node.left!=null){
                queue.add(node.left);
                floor.add(level+1);
            }
            if(node.right!=null){
                queue.add(node.right);
                floor.add(level+1);
            }
        }
        return result;
    }

}
